package com.info.zhiduoduo.core.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceUserType;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.constants.partner.PartnerBrokerageType;
import com.info.zhiduoduo.common.constants.pay.PaymentID;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.constants.project.CompanyProjectState;
import com.info.zhiduoduo.common.constants.project.ProjectType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.formbean.CalcProjectChargesFormBean;
import com.info.zhiduoduo.core.formbean.CheckProjectAmountFormBean;
import com.info.zhiduoduo.core.service.*;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.dto.maker.MakerYearAmountDto;
import com.info.zhiduoduo.repository.dto.maker.StudioDetailDto;
import com.info.zhiduoduo.repository.dto.project.*;
import com.info.zhiduoduo.repository.dto.quota.CompanyQuotaDto;
import com.info.zhiduoduo.repository.dto.quota.MakerQuotaDto;
import com.info.zhiduoduo.repository.dto.quota.ZhiduoduoCityQuotaDto;
import com.info.zhiduoduo.repository.entity.company.CompanyPayment;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.company.CompanyTax;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.partner.PartnerBrokerage;
import com.info.zhiduoduo.repository.entity.partner.PartnerCompany;
import com.info.zhiduoduo.repository.mapper.company.CompanyPaymentMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.entrustmentproject.EntrustmentProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerSubMapper;
import com.info.zhiduoduo.repository.mapper.quota.CompanyQuotaMapper;
import com.info.zhiduoduo.repository.mapper.quota.MakerQuotaMapper;
import com.info.zhiduoduo.repository.mapper.quota.ZhiduoduoCityQuotaMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
@Transactional
public class CoreProjectServiceImpl extends BaseService implements CoreProjectService {

	@Autowired
	MakerMapper makerMapper;
	@Autowired
	PartnerCompanyMapper partnerCompanyMapper;
	@Autowired
	PartnerBrokerageMapper partnerBrokerageMapper;
	@Autowired
	CompanyProjectMapper projectMapper;
	@Autowired
	CrowdsourceAccountMapper crowdsourceAccountMapper;
	@Autowired
	CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
	@Autowired
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Autowired
	MakerStudioMapper makerStudioMapper;
	@Autowired
	TaxerInvoiceMapper taxerInvoiceMapper;
	@Autowired
	PartnerSubMapper partnerSubMapper;
	@Autowired
	PartnerMapper partnerMapper;
	@Autowired
	EntrustmentProjectItemMapper entrustmentProjectItemMapper;
	@Autowired
	CompanyQuotaMapper companyQuotaMapper;
	@Autowired
	CompanyPaymentMapper companyPaymentMapper;
	@Autowired
	MakerQuotaMapper makerQuotaMapper;
	@Autowired
	ZhiduoduoCityQuotaMapper zhiduoduoCityQuotaMapper;

	@Autowired
	CoreCompanyService coreCompanyService;
	@Autowired
	DingdingNoticeService dingdingNoticeService;
	@Autowired
	WxMessageService wxMessageService;
	@Autowired
	WxPartnerMessageService wxPartnerMessageService;
	@Autowired
	WxCrowdsourceMessageService wxCrowdsourceMessageService;
	@Autowired
	CeoNoticeService ceoNoticeService;

	@Autowired
	CommonConfig commonConfig;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	PayConfig payConfig;

	@Override
	public void checkMakerQuota(int compid, int userid, int projectid, int projectType, BigDecimal currProjectAmount, int calcAmountType) {
		checkMakerQuota(compid, userid, projectid, projectType, currProjectAmount, currProjectAmount, calcAmountType, true);
	}

	@Override
	public void checkMakerQuota(int compid, int userid, int projectid, int projectType, BigDecimal currProjectAmount,BigDecimal makerProjectAmount, int calcAmountType,
	                            boolean checkCityQuota) {

		if (currProjectAmount == null) currProjectAmount = BigDecimal.ZERO;
		if (makerProjectAmount == null) makerProjectAmount = BigDecimal.ZERO;
		// 企业限额
		CompanyQuotaDto companyQuota = companyQuotaMapper.getByCompid(compid);

		// 创客必须有效
		MakerDetailDto makerStudio = makerMapper.getUserDetail(userid);
		Asserts.notNull(makerStudio, StatusMsg.StatusMsg_201);
		// 创客限额
		MakerQuotaDto makerQuota = makerQuotaMapper.getByUserid(userid);

		// 创客开户地城市限额, 需要检查才获取限额对象
		ZhiduoduoCityQuotaDto cityQuota = null;
		if (checkCityQuota) cityQuota = zhiduoduoCityQuotaMapper.getByConfigId(makerStudio.getOpeningLocation());

		// 系统年度限额判断
		Asserts.isTrue(getUserYearlyTotalAmount(userid, calcAmountType, projectid, projectType).add(makerProjectAmount).doubleValue() <=
				commonConfig.getYearlyStudioQuota(), StatusMsg.StatusMsg_207);
		// 过去12个月限额判断
		if (makerStudio.getTwelveMonthQuotaFlag() == Constants.TRUE) {
			Asserts.isTrue(
					getUserTwelveMonthTotalAmount(userid, calcAmountType, projectid, projectType).add(makerProjectAmount).doubleValue() <=
							commonConfig.getTwelveMonthStudioQuota(), StatusMsg.StatusMsg_246);
		}

		// 年度限额
		checkUserTotalAmountExceedYearlyQuota(companyQuota, makerQuota, cityQuota, projectid, projectType, makerProjectAmount,
				calcAmountType);
		// 季度限额
		checkUserTotalAmountExceedQuarterlyQuota(companyQuota, makerQuota, cityQuota, projectid, projectType, makerProjectAmount,
				calcAmountType);
		// 月度限额
		checkUserTotalAmountExceedMonthlyQuota(companyQuota, makerQuota, cityQuota, projectid, projectType, makerProjectAmount,
				calcAmountType);

		if (!ProjectType.isTaxerProject(projectType)) {// 和纯代理项目不判断单笔限额
			// 单笔限额
			checkUserTotalAmountExceedSingleQuota(companyQuota, makerQuota, cityQuota, projectid, projectType, currProjectAmount);
		}

		// 个人所有业务年度限额 项目： 、智众包、纯代理、智零工、创客团、委托接单
		if(ProjectType.isZhiduoduoProject(projectType) || ProjectType.isCrowdsourceProject(projectType) || ProjectType.isTaxerProject(projectType) || ProjectType.isInZddEntrustmentProjectTable(projectType)) {
			Asserts.isTrue(getTotalAmountByUserIdno(makerStudio.getIdno(), projectid, projectType, calcAmountType, 0).add(makerProjectAmount).compareTo(commonConfig.getUserIdnoYearQuota()) <= 0, StatusMsg.StatusMsg_271);
			// 个人所有业务12个月限额
			Asserts.isTrue(getTotalAmountByUserIdno(makerStudio.getIdno(), projectid, projectType, calcAmountType, 1).add(makerProjectAmount).compareTo(commonConfig.getUserIdnoTwelveMonthQuota()) <= 0, StatusMsg.StatusMsg_272);
		}
	}

	@Override
	public boolean checkUserTotalAmountExceedYearlyQuota(CompanyQuotaDto companyQuota, MakerQuotaDto makerQuota,
	                                                     ZhiduoduoCityQuotaDto cityQuota, int projectid, int projectType,
	                                                     BigDecimal currProjectAmount, int calcAmountType) {
		double totalAmount = getUserYearlyTotalAmountExcludeEntrusment(makerQuota.getUserid(), calcAmountType, projectid, projectType).add(
				currProjectAmount).doubleValue();
		if (NumberUtil.equals(makerQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(makerQuota.getYearlyQuota()), StatusMsg.StatusMsg_248);
		} else if (companyQuota != null && NumberUtil.equals(companyQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(companyQuota.getYearlyQuota()), StatusMsg.StatusMsg_247);
		} else if (cityQuota != null) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(cityQuota.getYearlyQuota()), StatusMsg.StatusMsg_249);
		}
		return true;
	}

	@Override
	public boolean checkUserTotalAmountExceedQuarterlyQuota(CompanyQuotaDto companyQuota, MakerQuotaDto makerQuota,
	                                                        ZhiduoduoCityQuotaDto cityQuota, int projectid, int projectType,
	                                                        BigDecimal currProjectAmount, int calcAmountType) {
		double totalAmount = getUserQuarterTotalAmountExcludeEntrustment(makerQuota.getUserid(), calcAmountType, projectid,
				projectType).add(currProjectAmount).doubleValue();
		if (NumberUtil.equals(makerQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(makerQuota.getQuarterlyQuota()), StatusMsg.StatusMsg_251);
		} else if (companyQuota != null && NumberUtil.equals(companyQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(companyQuota.getQuarterlyQuota()), StatusMsg.StatusMsg_250);
		} else if (cityQuota != null) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(cityQuota.getQuarterlyQuota()), StatusMsg.StatusMsg_252);
		}
		return true;
	}

	@Override
	public boolean checkUserTotalAmountExceedMonthlyQuota(CompanyQuotaDto companyQuota, MakerQuotaDto makerQuota,
	                                                      ZhiduoduoCityQuotaDto cityQuota, int projectid, int projectType,
	                                                      BigDecimal currProjectAmount, int calcAmountType) {
		double totalAmount = getUserMonthlyTotalAmountExcludeEntrustment(makerQuota.getUserid(), calcAmountType, projectid,
				projectType).add(currProjectAmount).doubleValue();
		if (NumberUtil.equals(makerQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(makerQuota.getMonthlyQuota()), StatusMsg.StatusMsg_254);
		} else if (companyQuota != null && NumberUtil.equals(companyQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(companyQuota.getMonthlyQuota()), StatusMsg.StatusMsg_253);
		} else if (cityQuota != null) {
			Asserts.isTrue(totalAmount <= NumberUtil.safeDouble(cityQuota.getMonthlyQuota()), StatusMsg.StatusMsg_255);
		}
		return true;
	}

	@Override
	public boolean checkUserTotalAmountExceedSingleQuota(CompanyQuotaDto companyQuota, MakerQuotaDto makerQuota,
	                                                     ZhiduoduoCityQuotaDto cityQuota, int projectid, int projectType,
	                                                     BigDecimal currProjectAmount) {
		if (makerQuota != null && NumberUtil.equals(makerQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(currProjectAmount.doubleValue() <= NumberUtil.safeDouble(makerQuota.getSingleQuota()), StatusMsg.StatusMsg_257);
		} else if (companyQuota != null && NumberUtil.equals(companyQuota.getQuotaFlag(), Constants.TRUE)) {
			Asserts.isTrue(currProjectAmount.doubleValue() <= companyQuota.getSingleQuota(), StatusMsg.StatusMsg_256);
		} else if (cityQuota != null) {
			Asserts.isTrue(currProjectAmount.doubleValue() <= NumberUtil.safeDouble(cityQuota.getSingleQuota()), StatusMsg.StatusMsg_258);
		}
		return true;
	}

	@Override
	public BigDecimal getUserYearlyTotalAmount(int userid, int calcAmountType) {
		return getUserYearlyTotalAmount(userid, calcAmountType, 0, 0);
	}

	@Override
	public BigDecimal getUserYearlyTotalAmount(int userid, int calcAmountType, int year) {
		return getUserYearlyTotalAmount(userid, calcAmountType, 0, 0, year);
	}

	@Override
	public BigDecimal getUserYearlyTotalAmount(int userid, int calcAmountType, boolean includeEntrustment) {
		return getUserYearlyTotalAmount(userid, calcAmountType, 0, 0, DateUtil.getNowYear(), true, includeEntrustment);
	}

	@Override
	public BigDecimal getUserYearlyTotalAmount(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserYearlyTotalAmount(userid, calcAmountType, projectid, projectType, DateUtil.getNowYear());
	}

	@Override
	public BigDecimal getUserYearlyTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year) {
		return getUserYearlyTotalAmount(userid, calcAmountType, projectid, projectType, year, true, true);
	}

	@Override
	public BigDecimal getUserYearlyTotalAmountExcludeCrowdsource(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserYearlyTotalAmount(userid, calcAmountType, projectid, projectType, DateUtil.getNowYear(), false, true);
	}

	@Override
	public BigDecimal getUserYearlyTotalAmountExcludeEntrusment(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserYearlyTotalAmount(userid, calcAmountType, projectid, projectType, DateUtil.getNowYear(), true, false);
	}

	@Override
	public BigDecimal getUserYearlyTotalAmountExcludeCrowdsourceEntrusment(int userid, int calcAmountType, int projectid,
	                                                                       int projectType) {
		return getUserYearlyTotalAmount(userid, calcAmountType, projectid, projectType, DateUtil.getNowYear(), false, false);
	}

	/**
	 * 包含创客以下项目金额: 项目+智众包项目+纯代理( )项目+支付宝委托发单项目
	 *
	 * @param userid
	 * @param calcAmountType     计算的项目金额类型, 取值于 {@link com.info.zhiduoduo.common.constants.project.CalcAmountType}
	 * @param projectid
	 * @param year
	 * @param includeCrowdsource
	 * @return
	 */
	public BigDecimal getUserYearlyTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year,
	                                           boolean includeCrowdsource, boolean includeEntrustment) {
		StudioDetailDto studio = makerStudioMapper.getStudioDetail(userid);
		if (studio == null) return BigDecimal.ZERO;

		Integer makerType = studio.getMakerType();
		BigDecimal yearlyTotalAmount = BigDecimal.ZERO;
		if (makerType == MakerType.INTELL || makerType == MakerType.CROWDSOURCE) {
			//  项目金额
			int zhiduoduoProjectid = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
			BigDecimal zhiduoduoAmount = projectMapper.getYearlyTotalAmountByStates(userid, zhiduoduoProjectid,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year);
			yearlyTotalAmount = yearlyTotalAmount.add(zhiduoduoAmount);

			// 委托发单/创客团的创客金额
			if (includeEntrustment) {
				int entrustProjectItemId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
				BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserYearTotalAmountByStates(userid, entrustProjectItemId,
						CalcAmountType.getEntrustProjectStates(calcAmountType), 0, year);
				yearlyTotalAmount = yearlyTotalAmount.add(entrustAmount);
			}

			// 智众包项目金额，判断是否需要包含智众包项目
			if (includeCrowdsource) {
				BigDecimal crowdsourceAmount;
				int crowdsourceProjectId = ProjectType.isInZddCrowdsourceProjectTable(projectType) ? projectid : 0;
				if (calcAmountType == CalcAmountType.ALL) {
					crowdsourceAmount = crowdsourceProjectItemMapper.getYearlyTotalProjectAmount(userid, CrowdsourceUserType.STUDIO,0,
							crowdsourceProjectId, year);
				} else {
					crowdsourceAmount = crowdsourceProjectItemMapper.getYearlyTotalProjectAmountByStates(userid, CrowdsourceUserType.STUDIO,0,
							crowdsourceProjectId, CalcAmountType.getCrowdsourceProjectStates(calcAmountType), year);
				}
				yearlyTotalAmount = yearlyTotalAmount.add(crowdsourceAmount);
			}

			//  创客开通了 功能，需要将已开发票的总金额累计起来。
			if (NumberUtil.safeInt(studio.getTaxer()) == 1) {
				int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
				BigDecimal taxerYearlyTotalAmount = taxerInvoiceMapper.getYearlyTotalAmountPaid(userid, invoiceid);
				yearlyTotalAmount = yearlyTotalAmount.add(taxerYearlyTotalAmount);
			}

		} else if (makerType == MakerType.TAXER) {

			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
			yearlyTotalAmount = taxerInvoiceMapper.getYearlyTotalAmountPaid(userid, invoiceid);
		}

		return yearlyTotalAmount;
	}

	/**
	 * 包含创客以下项目金额: 项目+智众包项目+纯代理( )项目+支付宝委托发单项目
	 *
	 * @param userid
	 * @param calcAmountType 计算的项目金额类型, 取值于 {@link com.info.zhiduoduo.common.constants.project.CalcAmountType}
	 * @return
	 */
	@Override
	public BigDecimal getUserTwelveMonthTotalAmount(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserTwelveMonthTotalAmount(userid, calcAmountType, projectid, projectType, true);
	}

	@Override
	public BigDecimal getUserTwelveMonthTotalAmountExcludeEntrusment(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserTwelveMonthTotalAmount(userid, calcAmountType, projectid, projectType, false);
	}

	public BigDecimal getUserTwelveMonthTotalAmount(int userid, int calcAmountType, int projectid, int projectType,
	                                                boolean includeEntrusment) {
		StudioDetailDto studio = makerStudioMapper.getStudioDetail(userid);
		if (studio == null) return BigDecimal.ZERO;

		Integer makerType = studio.getMakerType();
		BigDecimal twelveMonthTotalAmount = BigDecimal.ZERO;
		if (makerType == MakerType.INTELL || makerType == MakerType.CROWDSOURCE) {
			//  项目金额
			int zhiduoduoProjectid = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
			BigDecimal zhiduoduoAmount = projectMapper.getTwelveMonthTotalAmountByStates(userid, zhiduoduoProjectid,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType));
			twelveMonthTotalAmount = twelveMonthTotalAmount.add(zhiduoduoAmount);

			// 委托发单/创客团的创客金额
			if (includeEntrusment) {
				int entrustProjectItemId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
				BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserTwelveMonthTotalAmountByStates(userid, entrustProjectItemId,
						CalcAmountType.getEntrustProjectStates(calcAmountType));
				twelveMonthTotalAmount = twelveMonthTotalAmount.add(entrustAmount);
			}

			// 智众包项目金额，判断是否需要包含智众包项目
			BigDecimal crowdsourceAmount;
			int crowdsourceProjectId = ProjectType.isInZddCrowdsourceProjectTable(projectType) ? projectid : 0;
			if (calcAmountType == CalcAmountType.ALL) {
				crowdsourceAmount = crowdsourceProjectItemMapper.getTwelveMonthTotalProjectAmount(userid, CrowdsourceUserType.STUDIO,
						crowdsourceProjectId);
			} else {
				crowdsourceAmount = crowdsourceProjectItemMapper.getTwelveMonthTotalProjectAmountByStates(userid, CrowdsourceUserType.STUDIO,
						crowdsourceProjectId, CalcAmountType.getCrowdsourceProjectStates(calcAmountType));
			}
			twelveMonthTotalAmount = twelveMonthTotalAmount.add(crowdsourceAmount);

			//  创客开通了 功能，需要将已开发票的总金额累计起来。
			if (NumberUtil.safeInt(studio.getTaxer()) == 1) {
				int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
				BigDecimal taxerYearlyTotalAmount = taxerInvoiceMapper.getTwelveMonthTotalAmountPaid(userid, invoiceid);
				twelveMonthTotalAmount = twelveMonthTotalAmount.add(taxerYearlyTotalAmount);
			}

		} else if (makerType == MakerType.TAXER) {

			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
			twelveMonthTotalAmount = taxerInvoiceMapper.getTwelveMonthTotalAmountPaid(userid, invoiceid);
		}

		return twelveMonthTotalAmount;
	}

	@Override
	public BigDecimal getUserQuarterTotalAmount(int userid, int calcAmountType) {
		return getUserQuarterTotalAmount(userid, calcAmountType, 0, 0);
	}

	@Override
	public BigDecimal getUserQuarterTotalAmountByYearQuarter(int userid, int calcAmountType, int year, int quarter) {
		return getUserQuarterTotalAmount(userid, calcAmountType, 0, 0, year, quarter);
	}

	@Override
	public BigDecimal getUserQuarterTotalAmount(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserQuarterTotalAmount(userid, calcAmountType, projectid, projectType, 0, 0);
	}

	@Override
	public BigDecimal getUserQuarterTotalAmount(int userid, int calcAmountType, boolean includeEntrustment) {
		return getUserQuarterTotalAmount(userid, calcAmountType, 0, 0, 0, 0, true, includeEntrustment);
	}

	@Override
	public BigDecimal getUserQuarterTotalAmountExcludeEntrustment(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserQuarterTotalAmount(userid, calcAmountType, projectid, projectType, 0, 0, true, false);
	}

	private BigDecimal getUserQuarterTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year, int quarter) {
		return getUserQuarterTotalAmount(userid, calcAmountType, projectid, projectType, year, quarter, true, true);
	}

	private BigDecimal getUserQuarterTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year, int quarter,
	                                             boolean includeCrowdsource, boolean includeEntrustment) {
		StudioDetailDto studio = makerStudioMapper.getStudioDetail(userid);
		if (studio == null) return BigDecimal.ZERO;

		Integer makerType = studio.getMakerType();
		BigDecimal quarterTotalAmount = BigDecimal.ZERO;

		if (makerType == MakerType.INTELL || makerType == MakerType.CROWDSOURCE) {
			//当前是 创客

			// 智众包创客的智众包项目款,只有在计算 项目的季度/年度总金额时才会包含智众包项目款
			int zhiduoduoProjectid = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
			BigDecimal zhiduoduoAmount = projectMapper.getQuarterTotalAmountByStates(userid, zhiduoduoProjectid,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year, quarter);
			quarterTotalAmount = quarterTotalAmount.add(zhiduoduoAmount);

			// 委托发单/创客团的创客金额
			if (includeEntrustment) {
				int entrustProjectItemId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
				BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserQuarterTotalAmountByStates(userid, entrustProjectItemId,
						CalcAmountType.getEntrustProjectStates(calcAmountType), 0, year, quarter);
				quarterTotalAmount = quarterTotalAmount.add(entrustAmount);
			}

			// 智众包项目金额，判断是否需要包含智众包项目
			if (includeCrowdsource) {
				BigDecimal crowdsourceAmount;
				int crowdsourceProjectId = ProjectType.isInZddCrowdsourceProjectTable(projectType) ? projectid : 0;
				if (calcAmountType == CalcAmountType.ALL) {
					crowdsourceAmount = crowdsourceProjectItemMapper.getQuarterTotalProjectAmount(userid, CrowdsourceUserType.STUDIO,0,
							crowdsourceProjectId, year, quarter);
				} else {
					crowdsourceAmount = crowdsourceProjectItemMapper.getQuarterTotalProjectAmountByStates(userid, CrowdsourceUserType.STUDIO,0,
							crowdsourceProjectId, CalcAmountType.getCrowdsourceProjectStates(calcAmountType), year, quarter);
				}
				quarterTotalAmount = quarterTotalAmount.add(crowdsourceAmount);
			}

			// 创客开通了 功能，需要将已开发票的总金额累计起来。
			if (NumberUtil.safeInt(studio.getTaxer()) == 1) {
				int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
				BigDecimal taxerQuarterTotalAmount = taxerInvoiceMapper.getQuarterTotalAmountPaid(userid, invoiceid, year, quarter);
				quarterTotalAmount = quarterTotalAmount.add(taxerQuarterTotalAmount);
			}

		} else if (makerType == MakerType.TAXER) {

			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
			quarterTotalAmount = taxerInvoiceMapper.getQuarterTotalAmountPaid(userid, invoiceid, year, quarter);
		}

		return quarterTotalAmount;
	}

	@Override
	public BigDecimal getUserQuarterGenTotalAmountByYearQuarter(int userid, int calcAmountType, int year, int quarter) {
		return getUserQuarterGenTotalAmount(userid, calcAmountType, 0, 0, year, quarter, true);
	}

	@Override
	public BigDecimal getUserQuarterGenTotalAmountExcludeEntrustment(int userid, int calcAmountType, int projectid, int ProjectType) {
		return getUserQuarterGenTotalAmount(userid, calcAmountType, projectid, ProjectType, 0, 0, false);
	}

	private BigDecimal getUserQuarterGenTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year, int quarter,
	                                                boolean includeEntrustment) {
		StudioDetailDto studio = makerStudioMapper.getStudioDetail(userid);
		if (studio == null) return BigDecimal.ZERO;

		Integer makerType = studio.getMakerType();
		BigDecimal quarterGenTotalAmount = BigDecimal.ZERO;

		if (makerType == MakerType.INTELL) {
			// 创客 项目金额
			int zhiduoduoProjectid = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
			BigDecimal zhiduoduoAmount = projectMapper.getQuarterGenProjectTotalAmountByStates(userid, zhiduoduoProjectid,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year, quarter);
			quarterGenTotalAmount = quarterGenTotalAmount.add(zhiduoduoAmount);

			// 委托接单/创客的 项目金额
			if (includeEntrustment) {
				int entrustProjectItemId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
				String zhiduoduoProjectTypes = ProjectType.zhiduoduoProjectTypes();
				String entrustProjectStates = CalcAmountType.getEntrustProjectStates(calcAmountType);
				BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserQuarterGenTotalAmountByProjectTypeAndStates(userid,
						entrustProjectItemId, zhiduoduoProjectTypes, entrustProjectStates, year, quarter);
				quarterGenTotalAmount = quarterGenTotalAmount.add(entrustAmount);
			}

			if (NumberUtil.safeInt(studio.getTaxer()) == 1) {
				// 创客开通了 功能，需要将已开发票的总金额累计起来。
				int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
				BigDecimal taxerQuarterGenTotalAmount = taxerInvoiceMapper.getQuarterGenProjectTotalAmountPaid(userid, invoiceid, year,
						quarter);
				quarterGenTotalAmount = quarterGenTotalAmount.add(taxerQuarterGenTotalAmount);
			}
		} else if (makerType == MakerType.TAXER) {

			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
			quarterGenTotalAmount = taxerInvoiceMapper.getQuarterGenProjectTotalAmountPaid(userid, invoiceid, year, quarter);
		}

		return quarterGenTotalAmount;
	}

	@Override
	public BigDecimal getUserMonthlyTotalAmount(int userid) {
		return getUserMonthlyTotalAmount(userid, CalcAmountType.ALL);
	}

	@Override
	public BigDecimal getUserMonthlyTotalAmount(int userid, int calcAmountType) {
		return getUserMonthlyTotalAmount(userid, calcAmountType, 0, 0);
	}

	@Override
	public BigDecimal getUserMonthlyTotalAmount(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserMonthlyTotalAmount(userid, calcAmountType, projectid, projectType, 0, 0, true, true);
	}

	@Override
	public BigDecimal getUserMonthlyTotalAmountByYearMonth(int userid, int calcAmountType, int year, int month) {
		return getUserMonthlyTotalAmount(userid, calcAmountType, 0, 0, year, month, true, true);
	}

	@Override
	public BigDecimal getUserMonthlyTotalAmount(int userid, int calcAmountType, int year, int month, boolean includeEntrustment) {
		return getUserMonthlyTotalAmount(userid, calcAmountType, 0, 0, year, month, true, includeEntrustment);
	}

	@Override
	public BigDecimal getUserMonthlyTotalAmountExcludeEntrustment(int userid, int calcAmountType, int projectid, int projectType) {
		return getUserMonthlyTotalAmount(userid, calcAmountType, projectid, projectType, 0, 0, true, false);
	}

	public BigDecimal getUserMonthlyTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year, int month,
	                                            boolean includeCrowdsource, boolean includeEntrustment) {
		StudioDetailDto studio = makerStudioMapper.getStudioDetail(userid);
		if (studio == null) return BigDecimal.ZERO;

		Integer makerType = studio.getMakerType();
		BigDecimal monthTotalAmount = BigDecimal.ZERO;

		if (makerType == MakerType.INTELL || makerType == MakerType.CROWDSOURCE) {
			// 创客 项目金额
			int zhiduoduoProjectid = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
			BigDecimal zhiduoduoAmount = projectMapper.getMonthTotalAmountByStates(userid, zhiduoduoProjectid, 0,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year, month);
			monthTotalAmount = monthTotalAmount.add(zhiduoduoAmount);

			// 委托发单/创客团的创客金额，判断是否需要包含委托发单/创客团项目，微信端统计需要排除
			if (includeEntrustment) {
				int entrustProjectItemId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
				BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserMonthTotalAmountByStates(userid, entrustProjectItemId,
						CalcAmountType.getEntrustProjectStates(calcAmountType), 0, year, month);
				monthTotalAmount = monthTotalAmount.add(entrustAmount);
			}

			// 智众包项目金额，判断是否需要包含智众包项目
			if (includeCrowdsource) {
				BigDecimal crowdsourceAmount;
				int crowdsourceProjectId = ProjectType.isInZddCrowdsourceProjectTable(projectType) ? projectid : 0;
				if (calcAmountType == CalcAmountType.ALL) {
					crowdsourceAmount = crowdsourceProjectItemMapper.getMonthTotalProjectAmount(userid, CrowdsourceUserType.STUDIO,0,
							crowdsourceProjectId, year, month);
				} else {
					crowdsourceAmount = crowdsourceProjectItemMapper.getMonthlyTotalProjectAmountByStates(userid,
							CrowdsourceUserType.STUDIO,0, crowdsourceProjectId, CalcAmountType.getCrowdsourceProjectStates(calcAmountType),
							year, month);
				}
				monthTotalAmount = monthTotalAmount.add(crowdsourceAmount);
			}

			if (NumberUtil.safeInt(studio.getTaxer()) == 1) {
				// 创客开通了 功能，需要将已开发票的总金额累计起来。
				BigDecimal taxerQuarterGenTotalAmount = taxerInvoiceMapper.getMonthTotalAmount(userid, 0, year, month);
				monthTotalAmount = monthTotalAmount.add(taxerQuarterGenTotalAmount);
			}

		} else if (makerType == MakerType.TAXER) {

			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			monthTotalAmount = taxerInvoiceMapper.getMonthTotalAmount(userid, 0, year, month);
		}

		return monthTotalAmount;
	}

	@Override
	public BigDecimal getUserMonthlyGenTotalAmount(int userid, int calcAmountType, int projectid, int projectType, int year, int month,
	                                               boolean includeCrowdsource, boolean includeEntrustment) {
		StudioDetailDto studio = makerStudioMapper.getStudioDetail(userid);
		if (studio == null) return BigDecimal.ZERO;

		Integer makerType = studio.getMakerType();
		BigDecimal monthTotalAmount = BigDecimal.ZERO;

		if (makerType == MakerType.INTELL || makerType == MakerType.CROWDSOURCE) {
			// 创客 项目金额
			int zhiduoduoProjectid = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
			BigDecimal zhiduoduoAmount = projectMapper.getMonthTotalAmountByStates(userid, zhiduoduoProjectid, 1,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year, month);
			monthTotalAmount = monthTotalAmount.add(zhiduoduoAmount);

			// 委托发单/创客团的创客金额，判断是否需要包含委托发单/创客团项目，微信端统计需要排除
			if (includeEntrustment) {
				int entrustProjectItemId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
				BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserMonthTotalAmountByStates(userid, entrustProjectItemId,
						CalcAmountType.getEntrustProjectStates(calcAmountType), 1, year, month);
				monthTotalAmount = monthTotalAmount.add(entrustAmount);
			}

			// 智众包项目金额，判断是否需要包含智众包项目
			if (includeCrowdsource) {
				BigDecimal crowdsourceAmount;
				int crowdsourceProjectId = ProjectType.isInZddCrowdsourceProjectTable(projectType) ? projectid : 0;
				if (calcAmountType == CalcAmountType.ALL) {
					crowdsourceAmount = crowdsourceProjectItemMapper.getMonthGenTotalIntegratedAmount(userid, CrowdsourceUserType.STUDIO,
							crowdsourceProjectId, year, month);
				} else {
					crowdsourceAmount = crowdsourceProjectItemMapper.getMonthlyGenTotalIntegratedAmountByStates(userid,
							CrowdsourceUserType.STUDIO, crowdsourceProjectId, CalcAmountType.getCrowdsourceProjectStates(calcAmountType),
							year, month);
				}
				monthTotalAmount = monthTotalAmount.add(crowdsourceAmount);
			}

			if (NumberUtil.safeInt(studio.getTaxer()) == 1) {
				// 创客开通了 功能，需要将已开发票的总金额累计起来。
				BigDecimal taxerQuarterGenTotalAmount = taxerInvoiceMapper.getMonthGenTotalAmount(userid, 0, year, month);
				monthTotalAmount = monthTotalAmount.add(taxerQuarterGenTotalAmount);
			}

		} else if (makerType == MakerType.TAXER) {

			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			monthTotalAmount = taxerInvoiceMapper.getMonthGenTotalAmount(userid, 0, year, month);
		}

		return monthTotalAmount;
	}

	/**
	 * 统计创客全年税费, 包含 常规 项目 + 创客团项目 +  项目
	 */
	private BigDecimal getUserYearlyTaxFee(int userid, int calcAmountType, int projectid, int projectType) {
		// 常规 项目的税费
		int zhiduoduoProjectItemId = ProjectType.isInZddCompanyProjectTable(projectType) ? projectid : 0;
		BigDecimal zhiduoduoTaxFee = projectMapper.getMakerYearlyTaxFeeByStates(userid, zhiduoduoProjectItemId,
				CalcAmountType.getZhiduoduoProjectStates(calcAmountType));

		// 创客团项目的税费(不包含委托接单)
		int entrustProjectid = ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0;
		BigDecimal entrustTaxFee = entrustmentProjectItemMapper.sumUserYearZhiduoduoTaxFeeByStates(userid, entrustProjectid,
				CalcAmountType.getEntrustProjectStates(calcAmountType));

		//  项目的税费
		int invoiceid = ProjectType.TAXER == projectType ? projectid : 0;
		BigDecimal taxerYearlyTaxFee = taxerInvoiceMapper.getTaxerYearlyTaxFee(userid, invoiceid);
		return zhiduoduoTaxFee.add(entrustTaxFee).add(taxerYearlyTaxFee);
	}

	public SmartResult<CheckProjectAmountDto> checkCompanyUserTotalAmount(BaseSimpleFormBean<CheckProjectAmountFormBean> formBean) {
		CheckProjectAmountFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return smartResult(StatusMsg.StatusMsg_101);

		return smartResult(checkCompanyUserTotalAmount(reqdata));
	}

	@Override
	public CheckProjectAmountDto checkCompanyUserTotalAmount(CheckProjectAmountFormBean reqdata) {
		if (reqdata == null) return null;

		int projectid = reqdata.getProjectid();
		int userid = reqdata.getUserid();
		int compid = reqdata.getCompid();
		int invoicetype = reqdata.getInvoicetype();
		double projectamount = reqdata.getProjectamount() == null ? 0 : reqdata.getProjectamount().doubleValue();
		MakerStudio makerStudio = new MakerStudio().selectById(userid);

		//计算当前创客季度和年度总项目款,不包含委托接单项目金额
		double allQuarterTotalAmount = getUserQuarterTotalAmountExcludeEntrustment(userid, CalcAmountType.PROCESSING, projectid,ProjectType.ZHIDUODUO).doubleValue();
		double allYearlyTotalAmount = getUserYearlyTotalAmountExcludeEntrusment(userid, CalcAmountType.PROCESSING, projectid,ProjectType.ZHIDUODUO).doubleValue();

		double yearlyTotalAmount = projectMapper.getYearlyTotalAmountByCompid(userid, compid, projectid).doubleValue();
		double quarterTotalAmount = projectMapper.getQuarterTotalAmountByCompid(userid, compid, projectid,
				DateUtil.getQuarterOfDate(new Date()).value).doubleValue();
		BigDecimal todayAmount = projectMapper.getTodayAmount(compid, userid);

		int type = checkTotalAmountJustExceedType(allYearlyTotalAmount, allQuarterTotalAmount, projectamount);
		// 2021.06.27 判断当前这档服务费+税率跟上一档是一样的就不返回提示，因为现在150万以上都是一样的费率，提示就很奇怪
		double currTaxRate = getTaxRateByExceedType(makerStudio, invoicetype, type);
		double prevTaxRate = getTaxRateByExceedType(makerStudio, invoicetype, type - 1);
		if (NumberUtil.equals(currTaxRate, prevTaxRate)) {
			// 相同税率, 不需要提醒
			type = 0;
		}
		CalcProjectChargesFormBean calcformBean = new CalcProjectChargesFormBean(CalcAmountType.CHECKED, userid, compid, projectid, 0,
				ProjectType.ZHIDUODUO, invoicetype, reqdata.getProjectamount());
		CalcProjectChargesDto projectCharge = calcProjectCharge(calcformBean);

		return new CheckProjectAmountDto().setProjectid(projectid)
				.setQuarterTotalAmount(BigDecimal.valueOf(quarterTotalAmount))
				.setYearlyTotalAmount(BigDecimal.valueOf(yearlyTotalAmount))
				.setAllQuarterTotalAmount(BigDecimal.valueOf(allQuarterTotalAmount))
				.setAllYearlyTotalAmount(BigDecimal.valueOf(allYearlyTotalAmount))
				.setType(type)
				.setTaxFee(projectCharge.getTaxFee())
				.setServiceCharge(projectCharge.getServiceCharge())
				.setTodayAmount(todayAmount);
	}

	@Override
	public List<CheckProjectAmountDto> batchCheckCompanyUserTotalAmount(List<CompanyProject> list) {
		if (CollectionUtils.isEmpty(list)) return null;
		//获取公司id是否配置
		CompanyProject companyProject = list.get(0);
		CompanyTax companyTax = new CompanyTax().selectById(companyProject.getCompid());
		//按照用户分组
		Map<Integer, List<CompanyProject>> map = list.stream().collect(Collectors.groupingBy(CompanyProject::getUserid));

		List<CheckProjectAmountDto> returnList = new ArrayList<>();
		for (Integer userid : map.keySet()) {
			List<CompanyProject> projectList = map.get(userid);
			MakerStudio makerStudio = new MakerStudio().selectById(userid);
			//2023年2月22日  业务费率优化需求  发单接口判断企业费率是否开启，开启的话使用企业费率
			if (companyTax != null && NumberUtil.equals(companyTax.getCompanyTaxFlag(), Constants.TRUE)) {
				makerStudio.setGenLowServiceRate(companyTax.getGenLowServiceRate());
				makerStudio.setGenHighServiceRate(companyTax.getGenHighServiceRate());
				makerStudio.setGenHighTaxRate(companyTax.getGenHighTaxRate());
				makerStudio.setSpeServiceRate(companyTax.getSpeServiceRate());
				makerStudio.setSpeTaxRate(companyTax.getSpeTaxRate());
				makerStudio.setYearlyHighTaxRate(companyTax.getYearlyHighTaxRate());
				makerStudio.setYearlyHighServiceRate(companyTax.getYearlyHighServiceRate());
				makerStudio.setYearlyHigh2TaxRate(companyTax.getYearlyHigh2TaxRate());
				makerStudio.setYearlyHigh2ServiceRate(companyTax.getYearlyHigh2ServiceRate());
				makerStudio.setYearlyHigh3TaxRate(companyTax.getYearlyHigh3TaxRate());
				makerStudio.setYearlyHigh3ServiceRate(companyTax.getYearlyHigh3ServiceRate());
				makerStudio.setFixedService(companyTax.getFixedService());
				makerStudio.setFixedServiceRate(companyTax.getFixedServiceRate());
			}
			MakerAccount  makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
			//当前创客项目的金额 累加
			BigDecimal projectTotalAmount = BigDecimal.ZERO;
			//计算当前创客季度和年度进行中的项目款,不包含委托接单项目金额
			double allQuarterTotalAmount = getUserQuarterTotalAmountExcludeEntrustment(userid, CalcAmountType.PROCESSING, 0, ProjectType.ZHIDUODUO).doubleValue();
			double allYearlyTotalAmount = getUserYearlyTotalAmountExcludeEntrusment(userid, CalcAmountType.PROCESSING, 0, ProjectType.ZHIDUODUO).doubleValue();

			// 检测前创客所在税率档位
			int beforeType = checkTotalAmountType(allYearlyTotalAmount, allQuarterTotalAmount, 0);
			// 考虑发票类型一致情况下
			double beforeTaxRate = getTaxRateByExceedType(makerStudio, list.get(0).getInvoicetype(), beforeType);

			for (CompanyProject project : projectList) {
				int projectid = project.getProjectid();
				int compid = project.getCompid();
				BigDecimal projectamount = project.getProjectamount();
				projectTotalAmount = projectTotalAmount.add(projectamount);

				double yearlyTotalAmount = projectMapper.getYearlyTotalAmountByCompid(userid, compid, projectid).doubleValue();
				double quarterTotalAmount = projectMapper.getQuarterTotalAmountByCompid(userid, compid, projectid, DateUtil.getQuarterOfDate(new Date()).value).doubleValue();
				BigDecimal todayAmount = projectMapper.getTodayAmount(compid, userid);

				int currType = checkTotalAmountType(allYearlyTotalAmount, allQuarterTotalAmount, projectTotalAmount.doubleValue());
				// 判断当前这档服务费+税率跟上一档是一样的就不返回提示，因为现在150万以上都是一样的费率，提示就很奇怪
				double currTaxRate = getTaxRateByExceedType(makerStudio, project.getInvoicetype(), currType);
				if (NumberUtil.equals(currTaxRate, beforeTaxRate)) {
					// 相同税率, 判断前一笔项目的税率,如果也相同则不需要提示
					CompanyProject zddProject = projectMapper.getUserLastZddProject(userid, CalcAmountType.getZhiduoduoProjectStates(CompanyProjectState.PROCESSING));
					if (NumberUtil.equals(zddProject.getProjectTaxRate(), currTaxRate)) {
						currType = 0;
					}
				}

				CalcProjectChargesFormBean calcformBean = new CalcProjectChargesFormBean(CalcAmountType.PROCESSING, userid, compid, projectid, 0,
						ProjectType.ZHIDUODUO, project.getInvoicetype(), projectamount);
				CalcProjectChargesDto projectCharge = calcProjectCharge(calcformBean);

				returnList.add(new CheckProjectAmountDto().setProjectid(projectid)
														  .setQuarterTotalAmount(BigDecimal.valueOf(quarterTotalAmount))
														  .setYearlyTotalAmount(BigDecimal.valueOf(yearlyTotalAmount))
														  .setAllQuarterTotalAmount(BigDecimal.valueOf(allQuarterTotalAmount).add(projectTotalAmount))
														  .setAllYearlyTotalAmount(BigDecimal.valueOf(allYearlyTotalAmount).add(projectTotalAmount))
														  .setType(currType)
														  .setTaxFee(projectCharge.getTaxFee())
														  .setServiceCharge(projectCharge.getServiceCharge())
														  .setTodayAmount(todayAmount)
						                                  .setMakerName(makerAccount.getRealname())
									                      .setStudioName(makerStudio.getUsername()));
			}
		}
		return returnList;
	}

	private double getTaxRateByExceedType(MakerStudio studio, int invoiceType, int type) {
		switch (type) {
			case 5:
			case 4:
				return studio.getYearlyHigh3TaxRate();
			case 3:
				return studio.getYearlyHigh2TaxRate();
			case 2:
				return studio.getYearlyHighTaxRate();
			case 1:
				// 区分普票还是专票
				return invoiceType == 2 ? studio.getSpeTaxRate() : studio.getGenHighTaxRate();
			default:
				return 0;
		}
	}

	public SmartResult<AlertUserProjectAmountDto> checkUserTotalAmount(BaseSimpleFormBean<CheckProjectAmountFormBean> formBean) {
		CheckProjectAmountFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return smartResult(StatusMsg.StatusMsg_101);

		int projectid = reqdata.getProjectid();
		int userid = reqdata.getUserid();
		int compid = reqdata.getCompid();

		MakerStudio makerStudio = new MakerStudio().selectById(userid);
		if (makerStudio == null) return errorParamSmartResult();

		double projectamount = reqdata.getProjectamount() == null ? 0 : reqdata.getProjectamount().doubleValue();

		//计算当前创客季度和年度总项目款
		double quarterTotalAmount = getUserQuarterTotalAmountExcludeEntrustment(userid, CalcAmountType.CHECKING, projectid,
				ProjectType.ZHIDUODUO).doubleValue();
		double yearlyTotalAmount = getUserYearlyTotalAmountExcludeEntrusment(userid, CalcAmountType.CHECKING, projectid,
				ProjectType.ZHIDUODUO).doubleValue();

		int justExceedType = checkTotalAmountJustExceedType(yearlyTotalAmount, quarterTotalAmount, projectamount);
		int type = checkTotalAmountType(yearlyTotalAmount, quarterTotalAmount, projectamount);
		double ratio = 0;
		double totalAmount = 0;
		// 提醒类型：0：季度低于45万 1：超过季度45万 2：超过全年150万 3：超过全年300万 4：超过全年500万 5：超过全年500万
		switch (type) {
			case 1:
				totalAmount = quarterTotalAmount;
				ratio = NumberUtil.addDouble(makerStudio.getGenHighServiceRate(), makerStudio.getGenHighTaxRate());
				break;
			case 2:
				totalAmount = yearlyTotalAmount;
				ratio = NumberUtil.addDouble(makerStudio.getYearlyHighServiceRate(), makerStudio.getYearlyHighTaxRate());
				break;
			case 3:
				totalAmount = yearlyTotalAmount;
				ratio = NumberUtil.addDouble(makerStudio.getYearlyHigh2ServiceRate(), makerStudio.getYearlyHigh2TaxRate());
				break;
			case 4:
				totalAmount = yearlyTotalAmount;
				ratio = NumberUtil.addDouble(makerStudio.getYearlyHigh3ServiceRate(), makerStudio.getYearlyHigh3TaxRate());
				break;
			case 5:
				totalAmount = yearlyTotalAmount;
				ratio = NumberUtil.addDouble(makerStudio.getYearlyHigh3ServiceRate(), makerStudio.getYearlyHigh3TaxRate());
				break;
			default:
				totalAmount = quarterTotalAmount;
				ratio = makerStudio.getGenLowServiceRate();
				break;
		}

		double partnerProjectServiceRatio = partnerCompanyMapper.getValidList(compid, PartnerBrokerageType.PROJECT)
				.stream()
				.mapToDouble(PartnerCompany::getRatio)
				.sum();
		double totalRatio = NumberUtil.addDouble(ratio, partnerProjectServiceRatio);
		AlertUserProjectAmountDto amountDto = new AlertUserProjectAmountDto(BigDecimal.valueOf(totalAmount), totalRatio, justExceedType);

		return smartResult(amountDto);
	}

	public int checkTotalAmountJustExceedType(double currYearlyTotalAmount, double currQuarterTotalAcmount, double projectAmount) {
		double yearlyStudioQuota = commonConfig.getYearlyStudioQuota();
		double yearlyHigh3Amount = commonConfig.getYearlyHigh3Amount();
		double yearlyHigh2Amount = commonConfig.getYearlyHigh2Amount();
		double yearlyHighAmount = commonConfig.getYearlyHighAmount();
		double quarterSplitAmount = commonConfig.getGenQuarterSplitAmount();
		int type = 0;
		if (currYearlyTotalAmount <= yearlyStudioQuota && NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyStudioQuota) {
			//正好超过了年度限额
			type = 5;
		} else if (currYearlyTotalAmount <= yearlyHigh3Amount &&
				NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyHigh3Amount) {
			//正好超过年度3级高金额（500万）
			type = 4;
		} else if (currYearlyTotalAmount <= yearlyHigh2Amount &&
				NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyHigh2Amount) {
			//正好超过年度2级高金额（300万）
			type = 3;
		} else if (currYearlyTotalAmount <= yearlyHighAmount &&
				NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyHighAmount) {
			//正好超过年度1级高金额（150万）
			type = 2;
		} else if (currQuarterTotalAcmount <= quarterSplitAmount &&
				NumberUtil.addDouble(currQuarterTotalAcmount, projectAmount) > quarterSplitAmount) {
			//正好超过季度高金额（45万）
			type = 1;
		}
		return type;
	}

	public int checkTotalAmountType(double currYearlyTotalAmount, double currQuarterTotalAcmount, double projectAmount) {
		double yearlyStudioQuota = commonConfig.getYearlyStudioQuota();
		double yearlyHigh3Amount = commonConfig.getYearlyHigh3Amount();
		double yearlyHigh2Amount = commonConfig.getYearlyHigh2Amount();
		double yearlyHighAmount = commonConfig.getYearlyHighAmount();
		double quarterSplitAmount = commonConfig.getGenQuarterSplitAmount();
		int type = 0;
		if (NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyStudioQuota) {
			//超过了年度限额
			type = 5;
		} else if (NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyHigh3Amount) {
			//超过年度3级高金额（500万）
			type = 4;
		} else if (NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyHigh2Amount) {
			//超过年度2级高金额（300万）
			type = 3;
		} else if (NumberUtil.addDouble(currYearlyTotalAmount, projectAmount) > yearlyHighAmount) {
			//超过年度1级高金额（150万）
			type = 2;
		} else if (NumberUtil.addDouble(currQuarterTotalAcmount, projectAmount) > quarterSplitAmount) {
			//超过季度高金额（45万）
			type = 1;
		}
		return type;
	}

	/**
	 * 计算项目需要的服务费和税费
	 * <p> 根据dealded 确定采用projectdealamount还是projectamount来参与计算
	 * <p> 存在事务，就加入到事务中；不存在事务，就不创建自己的事务。
	 *
	 * @param formBean
	 * @return
	 */

	public CalcProjectChargesDto calcProjectCharge(CalcProjectChargesFormBean formBean) {
		if (formBean == null) return null;

		int calcAmountType = formBean.getCalcAmountType();
		int userid = formBean.getUserid();
		int compid = formBean.getCompid();
		int projectid = formBean.getProjectid();
		int parentProjectId = formBean.getParentProjectId();
		int invoicetype = formBean.getInvoicetype();
		BigDecimal amount = formBean.getAmount();
		int projectType = formBean.getProjectType();

		if (amount == null) return null;

		StudioDetailDto makerStudio = makerStudioMapper.getStudioDetail(userid);
		if (makerStudio == null) return null;
		//2023年2月22日  业务费率优化需求  发单接口判断企业费率是否开启，开启的话使用企业费率
		CompanyTax companyTax = new CompanyTax().selectById(compid);
		if (companyTax != null && NumberUtil.equals(companyTax.getCompanyTaxFlag(), Constants.TRUE)) {
			makerStudio.setGenLowServiceRate(companyTax.getGenLowServiceRate());
			makerStudio.setGenHighServiceRate(companyTax.getGenHighServiceRate());
			makerStudio.setGenHighTaxRate(companyTax.getGenHighTaxRate());
			makerStudio.setSpeServiceRate(companyTax.getSpeServiceRate());
			makerStudio.setSpeTaxRate(companyTax.getSpeTaxRate());
			makerStudio.setYearlyHighTaxRate(companyTax.getYearlyHighTaxRate());
			makerStudio.setYearlyHighServiceRate(companyTax.getYearlyHighServiceRate());
			makerStudio.setYearlyHigh2TaxRate(companyTax.getYearlyHigh2TaxRate());
			makerStudio.setYearlyHigh2ServiceRate(companyTax.getYearlyHigh2ServiceRate());
			makerStudio.setYearlyHigh3TaxRate(companyTax.getYearlyHigh3TaxRate());
			makerStudio.setYearlyHigh3ServiceRate(companyTax.getYearlyHigh3ServiceRate());
			makerStudio.setFixedService(companyTax.getFixedService());
			makerStudio.setFixedServiceRate(companyTax.getFixedServiceRate());
		}

		boolean isSpecialInvoice = invoicetype == 2;
		ProjectServiceChargeDto serviceCharge = calcStudioServiceCharge(makerStudio, compid, projectid, parentProjectId, projectType,
				isSpecialInvoice, amount, calcAmountType);
		ProjectTaxFeeDto taxFee = calcStudioTaxFee(makerStudio, projectid, projectType, isSpecialInvoice, amount, calcAmountType);

		return new CalcProjectChargesDto(serviceCharge.getServiceCharge(), taxFee.getTaxFee(), serviceCharge.getBaseServiceRatio(),
				serviceCharge.getPartnerProjectServiceRatio(), taxFee.getTaxRatio());
	}

	public ProjectServiceChargeDto calcStudioServiceCharge(StudioDetailDto studio, int compid, int projectid, int projectType,
	                                                       boolean isSpecialInvoice, BigDecimal dealAmount, int calcAmountType) {
		return calcStudioServiceCharge(studio, compid, projectid, 0, projectType, isSpecialInvoice, dealAmount, calcAmountType);
	}

	public ProjectServiceChargeDto calcStudioServiceCharge(StudioDetailDto studio, int compid, int projectid, int parentProjectId,
	                                                       int projectType, boolean isSpecialInvoice, BigDecimal dealAmount,
	                                                       int calcAmountType) {

		if (studio == null) return null;

		int userid = studio.getUserid();
		Integer makerType = studio.getMakerType();

		if (makerType == null) makerType = MakerType.INTELL;

		//所有合伙人方式的服务费佣金总费率。（合伙人方式的服务费佣金比例包含在基本服务费率里面）
		double partnerServiceRatio = 0;
		//所有合伙人的项目服务费佣金总费率。（项目服务费的佣金比例在基本服务费率的基础上再增加的）
		double partnerProjectServiceRatio = 0;

		// 只有创客开通了计算分佣的功能,才会确认项目的合伙人， 只有普通 项目和长期项目才需要判断创客的分佣开关
		if (NumberUtil.equals(studio.getBrokerageComputeState(), Constants.TRUE) || !ProjectType.isInZddCompanyProjectTable(projectType)) {
			// 创客团项目，分佣记录使用的是父项目id
			int brokerageProjectId = ProjectType.isInZddEntrustmentProjectTable(projectType) ? parentProjectId : projectid;
			partnerServiceRatio = partnerBrokerageMapper.getZhiduoduoProjectBrokerageList(brokerageProjectId, projectType,
					PartnerBrokerageType.BASIC).stream().mapToDouble(PartnerBrokerage::getRatio).sum();
			partnerProjectServiceRatio = partnerBrokerageMapper.getZhiduoduoProjectBrokerageList(brokerageProjectId, projectType,
					PartnerBrokerageType.PROJECT).stream().mapToDouble(PartnerBrokerage::getRatio).sum();
			// 还没有生成佣金记录, 获取配置的合伙人分佣比例
			// 纯代理或 申请开票的时候，合伙人分佣只从创客头上查，不查企业的分拥
			if (partnerServiceRatio == 0 && !ProjectType.isTaxerProject(projectType)) {
				partnerServiceRatio = partnerCompanyMapper.getValidList(compid, PartnerBrokerageType.BASIC)
						.stream()
						.mapToDouble(PartnerCompany::getRatio)
						.sum();
			}
			if (partnerProjectServiceRatio == 0 && !ProjectType.isTaxerProject(projectType)) {
				partnerProjectServiceRatio = partnerCompanyMapper.getValidList(compid, PartnerBrokerageType.PROJECT)
						.stream()
						.mapToDouble(PartnerCompany::getRatio)
						.sum();
			}
		}

		double baseServiceRate = getMakerBaseServiceRate(studio, projectid, projectType, isSpecialInvoice, dealAmount, calcAmountType);

		double totalServiceRatio = NumberUtil.addDouble(baseServiceRate, partnerProjectServiceRatio);
		BigDecimal serviceCharge = dealAmount.multiply(BigDecimal.valueOf(totalServiceRatio));
		BigDecimal partnerServiceCharge = dealAmount.multiply(BigDecimal.valueOf(partnerServiceRatio));
		BigDecimal partnerProjectServiceCharge = dealAmount.multiply(BigDecimal.valueOf(partnerProjectServiceRatio));

		return new ProjectServiceChargeDto().setServiceCharge(serviceCharge.setScale(2, RoundingMode.DOWN))
				.setTotalServiceRatio(totalServiceRatio)
				.setBaseServiceRatio(baseServiceRate)
				.setPartnerBaseServiceRatio(partnerServiceRatio)
				.setPartnerBaseServiceCharge(partnerServiceCharge)
				.setPartnerProjectServiceRatio(partnerProjectServiceRatio)
				.setPartnerProjectServiceCharge(partnerProjectServiceCharge);
	}

	@Override
	public double getMakerBaseServiceRate(StudioDetailDto studio, int projectid, int projectType, boolean isSpecialInvoice,
	                                      BigDecimal dealAmount, int calcAmountType) {
		int userid = studio.getUserid();
		double genLowServiceRate = 0;
		double genHighServiceRate = 0;
		double speServiceRate = 0;
		double yearlyHighServiceRate = 0;
		double yearlyHigh2ServiceRate = 0;
		double yearlyHigh3ServiceRate = 0;

		// if (makerType == MakerType.INTELL) {
		//当前是 创客 或智众包创客 开通了 功能，使用 工作室设置的各种服务费率
		genLowServiceRate = studio.getGenLowServiceRate();
		genHighServiceRate = studio.getGenHighServiceRate();
		speServiceRate = studio.getSpeServiceRate();
		yearlyHighServiceRate = studio.getYearlyHighServiceRate();
		yearlyHigh2ServiceRate = studio.getYearlyHigh2ServiceRate();
		yearlyHigh3ServiceRate = studio.getYearlyHigh3ServiceRate();

		/*} else if (makerType == MakerType.TAXER) {
			// 2021.4.27  开票计算税费, 使用单独的阶梯费率. CoreTaxerService.calculateTaxerInvoice()
			//当前是 创客
			genLowServiceRate = studio.getTaxerGenLowServiceRate();
			genHighServiceRate = studio.getTaxerGenLowServiceRate();
			speServiceRate = studio.getTaxerGenLowServiceRate();
			yearlyHighServiceRate = studio.getTaxerGenLowServiceRate();
			yearlyHigh2ServiceRate = studio.getTaxerGenLowServiceRate();
			yearlyHigh3ServiceRate = studio.getTaxerGenLowServiceRate();
		}*/

		BigDecimal quarterTotalAmount = getUserQuarterTotalAmountExcludeEntrustment(userid, calcAmountType, projectid, projectType);
		BigDecimal yearlyTotalAmount = getUserYearlyTotalAmountExcludeEntrusment(userid, calcAmountType, projectid, projectType);

		double baseServiceRate;
		int type = checkTotalAmountType(yearlyTotalAmount.doubleValue(), quarterTotalAmount.doubleValue(), dealAmount.doubleValue());
		// 类型：0：季度低于45万 1：超过季度45万 2：超过全年150万 3：超过全年300万 4：超过全年500万 5：超过全年500万
		switch (type) {
			case 5:
				baseServiceRate = yearlyHigh3ServiceRate;
				break;
			case 4:
				baseServiceRate = yearlyHigh3ServiceRate;
				break;
			case 3:
				baseServiceRate = yearlyHigh2ServiceRate;
				break;
			case 2:
				baseServiceRate = yearlyHighServiceRate;
				break;
			case 1:
				//75万以下，判断是专票还是普票
				baseServiceRate = isSpecialInvoice ? speServiceRate : genHighServiceRate;
				break;
			case 0:
			default:
				//30万以下，判断是专票还是普票
				baseServiceRate = isSpecialInvoice ? speServiceRate : genLowServiceRate;
				break;
		}
		return baseServiceRate;
	}

	public ProjectTaxFeeDto calcStudioTaxFee(StudioDetailDto studio, int projectid, int projectType, boolean isSpecialInvoice,
	                                         BigDecimal dealAmount, int calcAmountType) {
		if (studio == null) return null;

		int userid = studio.getUserid();
		Integer makerType = studio.getMakerType();

		if (makerType == null) makerType = MakerType.INTELL;

		double speTaxRate = 0;
		double genHighTaxRate = 0;
		double yearlyHighTaxRate = 0;
		double yearlyHigh2TaxRate = 0;
		double yearlyHigh3TaxRate = 0;
		// if (makerType == MakerType.INTELL) {
		//当前是 创客 或智众包创客
		speTaxRate = studio.getSpeTaxRate();
		genHighTaxRate = studio.getGenHighTaxRate();
		yearlyHighTaxRate = studio.getYearlyHighTaxRate();
		yearlyHigh2TaxRate = studio.getYearlyHigh2TaxRate();
		yearlyHigh3TaxRate = studio.getYearlyHigh3TaxRate();

		/*} else if (makerType == MakerType.TAXER) {
			// 2021.4.27  开票计算税费, 使用单独的阶梯费率. CoreTaxerService.calculateTaxerInvoice()
			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			//这里获取的税率都是0，其计算结果税费也都是0.
			speTaxRate = studio.getTaxerSpeTaxRate();
			genHighTaxRate = studio.getTaxerGenHighTaxRate();
			yearlyHighTaxRate = studio.getTaxerYearlyHighTaxRate();
			yearlyHigh2TaxRate = studio.getTaxerYearlyHighTaxRate();
			yearlyHigh3TaxRate = studio.getTaxerYearlyHighTaxRate();
		}*/

		BigDecimal quarterTotalAmount = getUserQuarterTotalAmountExcludeEntrustment(userid, calcAmountType, projectid, projectType);
		BigDecimal yearlyTotalAmount = getUserYearlyTotalAmountExcludeEntrusment(userid, calcAmountType, projectid, projectType);
		BigDecimal yearlyTotalAmountExcludeCrowdsource = getUserYearlyTotalAmountExcludeCrowdsourceEntrusment(userid, calcAmountType,
				projectid, projectType);
		BigDecimal quarterGenProjectTotalAmount = getUserQuarterGenTotalAmountExcludeEntrustment(userid, calcAmountType, projectid,
				projectType);
		//除去当前项目的以前所有项目已缴纳的税费
		BigDecimal totalTaxFee = getUserYearlyTaxFee(userid, calcAmountType, projectid, projectType);

		// 加上当前项目金额后：0：无 1：正好超过季度45万 2：正好超过全年150万 3：正好超过全年300万 4：正好超过全年500万 5：正好超过全年500万
		// int justExceedType = checkTotalAmountJustExceedType(yearlyTotalAmount.doubleValue(), quarterTotalAmount.doubleValue(),
		// 		dealAmount.doubleValue());

		// 加上当前项目金额后：0：季度低于45万 1：超过季度45万 2：超过全年150万 3：超过全年300万 4：超过全年500万 5：超过全年500万
		int type = checkTotalAmountType(yearlyTotalAmount.doubleValue(), quarterTotalAmount.doubleValue(), dealAmount.doubleValue());

		double taxRatio = getMakerBaseTaxRate(studio, projectid, projectType, isSpecialInvoice, dealAmount, calcAmountType);
		//当前应交的服务费
		BigDecimal taxFee;
		if (type == 4 || type == 5) {
			//4：超过全年500万 5：超过全年500万
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			//4：正好超过全年500万 需要补齐之前的税费
			// if (justExceedType == 4) taxFee = taxFee.add(getArrears(yearlyTotalAmountExcludeCrowdsource, totalTaxFee, taxRatio));
			taxFee = taxFee.add(getArrears(yearlyTotalAmountExcludeCrowdsource, totalTaxFee, taxRatio));
		} else if (type == 3) {
			//3：超过全年300万
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			// 正好超过全年300万 需要补齐之前的税费
			// if (justExceedType == 3) taxFee = taxFee.add(getArrears(yearlyTotalAmountExcludeCrowdsource, totalTaxFee, taxRatio));
			taxFee = taxFee.add(getArrears(yearlyTotalAmountExcludeCrowdsource, totalTaxFee, taxRatio));
		} else if (type == 2) {
			// 2：超过全年150万
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			// 正好超过全年150万 需要补齐之前的税费
			// if (justExceedType == 2) taxFee = taxFee.add(getArrears(yearlyTotalAmountExcludeCrowdsource, totalTaxFee, taxRatio));
			taxFee = taxFee.add(getArrears(yearlyTotalAmountExcludeCrowdsource, totalTaxFee, taxRatio));
		} else if (type == 1) {
			// 1：超过季度45万
			//判断是专票或普票
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			//正好超过季度限额,需要补交之前普票项目的税金
			// if (justExceedType == 1) taxFee = taxFee.add(getArrears(quarterGenProjectTotalAmount, BigDecimal.ZERO, genHighTaxRate));
			taxFee = taxFee.add(getArrears(quarterGenProjectTotalAmount, totalTaxFee, genHighTaxRate));
		} else {
			// 0：季度低于45万
			//判断是专票或普票，45万以下，普票不交税
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));
		}

		//更新项目的税率和税费
		if (projectid != 0 && projectType == ProjectType.ZHIDUODUO) {
			new CompanyProject().setProjectid(projectid).setProjectTaxRate(taxRatio).setProjecttaxfee(taxFee).updateById();
		}

		return new ProjectTaxFeeDto(taxFee.setScale(2, RoundingMode.DOWN), taxRatio);
	}

	@Override
	public double getMakerBaseTaxRate(StudioDetailDto studio, int projectid, int projectType, boolean isSpecialInvoice,
	                                  BigDecimal dealAmount, int calcAmountType) {
		int userid = studio.getUserid();
		double speTaxRate = 0;
		double genHighTaxRate = 0;
		double yearlyHighTaxRate = 0;
		double yearlyHigh2TaxRate = 0;
		double yearlyHigh3TaxRate = 0;
		// if (makerType == MakerType.INTELL) {
		//当前是 创客 或智众包创客
		speTaxRate = studio.getSpeTaxRate();
		genHighTaxRate = studio.getGenHighTaxRate();
		yearlyHighTaxRate = studio.getYearlyHighTaxRate();
		yearlyHigh2TaxRate = studio.getYearlyHigh2TaxRate();
		yearlyHigh3TaxRate = studio.getYearlyHigh3TaxRate();

		/*} else if (makerType == MakerType.TAXER) {
			// 2021.4.27  开票计算税费, 使用单独的阶梯费率. CoreTaxerService.calculateTaxerInvoice()
			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			//这里获取的税率都是0，其计算结果税费也都是0.
			speTaxRate = studio.getTaxerSpeTaxRate();
			genHighTaxRate = studio.getTaxerGenHighTaxRate();
			yearlyHighTaxRate = studio.getTaxerYearlyHighTaxRate();
			yearlyHigh2TaxRate = studio.getTaxerYearlyHighTaxRate();
			yearlyHigh3TaxRate = studio.getTaxerYearlyHighTaxRate();
		}*/

		BigDecimal quarterTotalAmount = getUserQuarterTotalAmountExcludeEntrustment(userid, calcAmountType, projectid, projectType);
		BigDecimal yearlyTotalAmount = getUserYearlyTotalAmountExcludeEntrusment(userid, calcAmountType, projectid, projectType);

		// 加上当前项目金额后：0：季度低于45万 1：超过季度45万 2：超过全年150万 3：超过全年300万 4：超过全年500万 5：超过全年500万
		int type = checkTotalAmountType(yearlyTotalAmount.doubleValue(), quarterTotalAmount.doubleValue(), dealAmount.doubleValue());

		double taxRatio = 0;
		if (type == 4 || type == 5) {
			//4：超过全年500万 5：超过全年500万
			taxRatio = yearlyHigh3TaxRate;
		} else if (type == 3) {
			//3：超过全年300万
			taxRatio = yearlyHigh2TaxRate;
		} else if (type == 2) {
			// 2：超过全年150万
			taxRatio = yearlyHighTaxRate;
		} else if (type == 1) {
			// 1：超过季度45万
			//判断是专票或普票
			taxRatio = isSpecialInvoice ? speTaxRate : genHighTaxRate;
		} else {
			// 0：季度低于45万
			//判断是专票或普票，45万以下，普票不交税
			taxRatio = isSpecialInvoice ? speTaxRate : 0;
		}

		return taxRatio;
	}

	public ProjectTaxFeeDto fixTaxFee(StudioDetailDto studio, CompanyProject project) {
		if (studio == null) return null;

		int userid = studio.getUserid();
		Integer makerType = studio.getMakerType();

		if (makerType == null) makerType = MakerType.INTELL;

		BigDecimal dealAmount = project.getProjectdealamount();
		boolean isSpecialInvoice = NumberUtil.safeInt(project.getInvoicetype()) == 2;

		double speTaxRate = 0;
		double genHighTaxRate = 0;
		double yearlyHighTaxRate = 0;
		double yearlyHigh2TaxRate = 0;
		double yearlyHigh3TaxRate = 0;
		// if (makerType == MakerType.INTELL) {
		//当前是 创客 或智众包创客
		speTaxRate = studio.getSpeTaxRate();
		genHighTaxRate = studio.getGenHighTaxRate();
		yearlyHighTaxRate = studio.getYearlyHighTaxRate();
		yearlyHigh2TaxRate = studio.getYearlyHigh2TaxRate();
		yearlyHigh3TaxRate = studio.getYearlyHigh3TaxRate();

		/*} else if (makerType == MakerType.TAXER) {
			// 2021.4.27  开票计算税费, 使用单独的阶梯费率. CoreTaxerService.calculateTaxerInvoice()
			//当前是 创客
			//目前版本， 创客每月只有10万的开票额度，季度肯定不会超过30万，所以都是免税的。
			//这里获取的税率都是0，其计算结果税费也都是0.
			speTaxRate = studio.getTaxerSpeTaxRate();
			genHighTaxRate = studio.getTaxerGenHighTaxRate();
			yearlyHighTaxRate = studio.getTaxerYearlyHighTaxRate();
			yearlyHigh2TaxRate = studio.getTaxerYearlyHighTaxRate();
			yearlyHigh3TaxRate = studio.getTaxerYearlyHighTaxRate();
		}*/

		Date projectcheckend = project.getProjectcheckend();
		BigDecimal quarterTotalAmount = projectMapper.getQuarterTotalAmountBefore(userid, projectcheckend);
		BigDecimal yearlyTotalAmount = projectMapper.getYearlyTotalAmountBefore(userid, projectcheckend);
		BigDecimal quarterGenProjectTotalAmount = projectMapper.getQuarterGenProjectTotalAmountBefore(userid, projectcheckend);
		//除去当前项目的以前所有项目已缴纳的税费
		BigDecimal totalTaxFee = projectMapper.getUserYearlyTaxFeeBefore(userid, projectcheckend);

		// 加上当前项目金额后：0：无 1：正好超过季度45万 2：正好超过全年150万 3：正好超过全年300万 4：正好超过全年500万 5：正好超过全年500万
		int justExceedType = checkTotalAmountJustExceedType(yearlyTotalAmount.doubleValue(), quarterTotalAmount.doubleValue(),
				dealAmount.doubleValue());

		// 加上当前项目金额后：0：季度低于45万 1：超过季度45万 2：超过全年150万 3：超过全年300万 4：超过全年500万 5：超过全年500万
		int type = checkTotalAmountType(yearlyTotalAmount.doubleValue(), quarterTotalAmount.doubleValue(), dealAmount.doubleValue());

		//当前应交的服务费
		BigDecimal taxFee;
		double taxRatio = 0;
		if (type == 4 || type == 5) {
			//4：超过全年500万 5：超过全年500万
			taxRatio = yearlyHigh3TaxRate;
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			//4：正好超过全年500万 需要补齐之前的税费
			if (justExceedType == 4) taxFee = taxFee.add(getArrears(yearlyTotalAmount, totalTaxFee, taxRatio));
		} else if (type == 3) {
			//3：超过全年300万
			taxRatio = yearlyHigh2TaxRate;
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			// 正好超过全年300万 需要补齐之前的税费
			if (justExceedType == 3) taxFee = taxFee.add(getArrears(yearlyTotalAmount, totalTaxFee, taxRatio));
		} else if (type == 2) {
			// 2：超过全年150万
			taxRatio = yearlyHighTaxRate;
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			// 正好超过全年150万 需要补齐之前的税费
			if (justExceedType == 2) taxFee = taxFee.add(getArrears(yearlyTotalAmount, totalTaxFee, taxRatio));
		} else if (type == 1) {
			// 1：超过季度45万
			//判断是专票或普票
			taxRatio = isSpecialInvoice ? speTaxRate : genHighTaxRate;
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));

			//正好超过季度限额,需要补交之前普票项目的税金
			if (justExceedType == 1) taxFee = taxFee.add(getArrears(quarterGenProjectTotalAmount, BigDecimal.ZERO, genHighTaxRate));
		} else {
			// 0：季度低于45万
			//判断是专票或普票，45万以下，普票不交税
			taxRatio = isSpecialInvoice ? speTaxRate : 0;
			taxFee = dealAmount.multiply(BigDecimal.valueOf(taxRatio));
		}

		return new ProjectTaxFeeDto(taxFee.setScale(2, RoundingMode.DOWN), taxRatio);
	}

	/**
	 * 获取需要补缴的金额
	 *
	 * @param totalAmount  历史已交易的项目总金额
	 * @param handedTaxFee 历史已交易的项目总税金
	 * @param taxRatio     最新的税率（按此税率补缴）
	 * @return
	 */
	private BigDecimal getArrears(BigDecimal totalAmount, BigDecimal handedTaxFee, double taxRatio) {
		BigDecimal totalHighTaxFee = totalAmount.multiply(BigDecimal.valueOf(taxRatio));

		//应付欠款,补交金额
		BigDecimal arrears = BigDecimal.ZERO;
		if (totalHighTaxFee.compareTo(handedTaxFee) > 0) {
			//应付的税金大于实际已付的，需要补交
			arrears = totalHighTaxFee.subtract(handedTaxFee);
		}
		return arrears;
	}

	@Override
	public SmartResult<ProjectDto> getUserLastProject(BaseSimpleFormBean<String> formBean) {
		int compid = formBean.getUserid();
		@Valid String userids = formBean.getReqdata();
		if (StringUtil.isEmpty(userids)) return SmartResult.ofErrorParam();

		List<ProjectDto> list = Stream.of(userids.split(","))
				.map(StringUtil::toInt)
				.map(userid -> projectMapper.getuserLastProject(compid, userid, 0))
				.filter(Objects::nonNull)
				.collect(Collectors.toList());

		if (list.size() == 1) {
			return SmartResult.success(list.get(0));
		}
		return SmartResult.success(list);
	}

	@Override
	public List<SameProjectDto> getTimeSameZddTradeAmount(String projectIds,Integer compid) {
		List<SameProjectDto> sameList = new ArrayList<>();
		//获取项目状态值
		String zddStatusAll = CalcAmountType.getZhiduoduoProjectStates(CalcAmountType.ALL);
		String zddStatus = CalcAmountType.getZhiduoduoProjectStates(CalcAmountType.PROCESSING);

		// 需要校验的项目
		List<SameProjectDto> validProjectList = projectMapper.getTimeSlotProject(2, compid, zddStatusAll, projectIds);

		//判断项目是否有重复创客重复金额
		sameList = validProjectList.stream()
						.collect(Collectors.toMap(e -> e.format(e), e -> 1, Integer::sum)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
						.entrySet().stream().filter(entry -> entry.getValue() > 1)
						.map(Map.Entry::getKey).collect(Collectors.toList());

		// 去掉重复用户+金额的数据
		validProjectList = validProjectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getProjectAmount()))), ArrayList::new));


		// 获取企业的项目数据 selectType=1：15分钟内交易的数据 selectType=2：根据项目ID查询
		// 15分钟内提交的项目
		List<SameProjectDto> finishProjectList = projectMapper.getTimeSlotProject(1,compid, zddStatus,projectIds);

		// 去掉重复用户+金额的数据
		finishProjectList = finishProjectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getProjectAmount()))), ArrayList::new));

		// 合并集合，对比项目金额是否存在已提交的项目中
		validProjectList.addAll(finishProjectList);

		//判断项目是否有重复创客重复金额
		sameList.addAll(validProjectList.stream()
							.collect(Collectors.toMap(e -> e.format(e), e -> 1, Integer::sum)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
							.entrySet().stream().filter(entry -> entry.getValue() > 1)
							.map(Map.Entry::getKey).collect(Collectors.toList()));

		if (CollectionUtils.isNotEmpty(sameList)) {
			sameList = sameList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getProjectAmount()))), ArrayList::new));
			return sameList;
		}
		return null;
	}

	@Override
	public List<SameProjectDto> getTimeSameCroTradeAmount(String projectIds,Integer compid) {
		List<SameProjectDto> sameList = new ArrayList<>();
		//获取项目状态值
		String croStatusAll = CalcAmountType.getCrowdsourceProjectStates(CalcAmountType.ALL);
		String croStatus = CalcAmountType.getCrowdsourceProjectStates(CalcAmountType.PROCESSING);

		// 需要校验的项目
		List<SameProjectDto> validProjectList = crowdsourceProjectItemMapper.getTimeSlotProject(2, compid, croStatusAll, projectIds);

		//判断项目是否有重复创客重复金额
		sameList = validProjectList.stream()
						.collect(Collectors.toMap(e -> e.format(e), e -> 1, Integer::sum)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
						.entrySet().stream().filter(entry -> entry.getValue() > 1)
						.map(Map.Entry::getKey).collect(Collectors.toList());

		// 去掉重复用户+金额的数据
		validProjectList = validProjectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getUserType() + t.getProjectAmount()))), ArrayList::new));


		// 获取企业的项目数据 selectType=1：15分钟内交易的数据 selectType=2：根据项目ID查询
		// 15分钟内提交的项目
		List<SameProjectDto> finishProjectList = crowdsourceProjectItemMapper.getTimeSlotProject(1,compid, croStatus, projectIds);

		// 去掉重复用户+金额的数据
		finishProjectList = finishProjectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getUserType() + t.getProjectAmount()))), ArrayList::new));

		// 合并集合，对比项目金额是否存在已提交的项目中
		validProjectList.addAll(finishProjectList);

		//判断项目是否有重复创客重复金额
		sameList.addAll(validProjectList.stream()
							.collect(Collectors.toMap(e -> e.format(e), e -> 1, Integer::sum)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
							.entrySet().stream().filter(entry -> entry.getValue() > 1)
							.map(Map.Entry::getKey).collect(Collectors.toList()));

		if (CollectionUtils.isNotEmpty(sameList)) {
			sameList = sameList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getUserType() + t.getProjectAmount()))), ArrayList::new));
			return sameList;
		}
		return null;
	}

	@Override
	public List<SameProjectDto> getTimeSameEntTradeAmount(String projectIds){
		List<SameProjectDto> sameList = new ArrayList<>();
		//获取项目状态值
		String entStatusAll = CalcAmountType.getEntrustProjectStates(CalcAmountType.ALL);
		String entStatus = CalcAmountType.getEntrustProjectStates(CalcAmountType.PROCESSING);

		// 需要校验的项目
		List<SameProjectDto> validProjectList = entrustmentProjectItemMapper.getTimeSlotProject(2, entStatusAll, projectIds);

		//判断项目是否有重复用户重复金额
		sameList = validProjectList.stream()
								   .collect(Collectors.toMap(e -> e.format(e), e -> 1, Integer::sum)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
								   .entrySet().stream().filter(entry -> entry.getValue() > 1)
								   .map(Map.Entry::getKey).collect(Collectors.toList());

		// 去掉重复用户+金额的数据
		validProjectList = validProjectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getProjectAmount()))), ArrayList::new));


		// 获取企业的项目数据 selectType=1：15分钟内交易的数据 selectType=2：根据项目ID查询
		// 15分钟内提交的项目
		List<SameProjectDto> finishProjectList = entrustmentProjectItemMapper.getTimeSlotProject(1, entStatus, projectIds);

		// 去掉重复用户+金额的数据
		finishProjectList = finishProjectList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getProjectAmount()))), ArrayList::new));

		// 合并集合，对比项目金额是否存在已提交的项目中
		validProjectList.addAll(finishProjectList);

		//判断项目是否有重复创客重复金额
		sameList.addAll(validProjectList.stream()
										.collect(Collectors.toMap(e -> e.format(e), e -> 1, Integer::sum)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
										.entrySet().stream().filter(entry -> entry.getValue() > 1)
										.map(Map.Entry::getKey).collect(Collectors.toList()));

		if (CollectionUtils.isNotEmpty(sameList)) {
			sameList = sameList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> "" + t.getUserid() + t.getProjectAmount()))), ArrayList::new));
			return sameList;
		}
		return null;
	}

	public SmartResult checkCompanyAccountForProject(int compid, Integer payId, BigDecimal projectAmount) {
		//获取企业余额信息
		CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(compid,payId);
		if (companyPayment == null) return smartResult(StatusMsg.StatusMsg_330);

		//如果企业是线下银行支付的，直接返回，不需要验证余额
		if (PaymentID.BLT_2.equals(payId)) {
			return smartResult();
		}

		// 判断企业账户余额是否充足
		BigDecimal balance = companyPayment.getBalance();
		if (balance.compareTo(projectAmount) < 0) {
			//余额不足,返回报错
			return SmartResult.fail(StatusMsg.StatusMsg_365);
		}
		return SmartResult.success();
	}

	@Override
	public BigDecimal getTotalAmountByCompids(String compids, Date from, Date to) {
		BigDecimal zhiduoduoAmount = projectMapper.getTotalAmountByCompids(compids, from, to);
		BigDecimal crowdsourceAmount = crowdsourceProjectItemMapper.getTotalAmountByCompids(compids, from, to);
		BigDecimal entrustAmount = entrustmentProjectItemMapper.getTotalAmountByCompids(compids, from, to);
		return zhiduoduoAmount.add(crowdsourceAmount).add(entrustAmount);
	}

	@Override
	public BigDecimal getTotalAmountByUserid(int userid, Date from, Date to) {
		BigDecimal zhiduoduoAmount = projectMapper.getTotalAmountByUserid(userid, from, to);
		BigDecimal crowdsourceAmount = crowdsourceProjectItemMapper.getTotalAmountByUserid(userid, from, to);
		BigDecimal entrustAmount = entrustmentProjectItemMapper.getTotalAmountByUserid(userid, from, to);
		return zhiduoduoAmount.add(crowdsourceAmount).add(entrustAmount);
	}

	/**
	 * 查询创客项目交易金额 包含(进行中、验收中、已验收、已完成)项目类型： 、智众包、委托接单、创客团
	 *
	 * @param userid
	 * @param from
	 * @param to
	 * @return
	 */
	@Override
	public BigDecimal getTotalAmountByUserId(int userid, Date from, Date to) {
		String zddStatus = CalcAmountType.getZhiduoduoProjectStates(CalcAmountType.PROCESSING);
		String crowdsourceStatus = CalcAmountType.getCrowdsourceProjectStates(CalcAmountType.PROCESSING);
		String entrustStatus = CalcAmountType.getEntrustProjectStates(CalcAmountType.PROCESSING);

		BigDecimal zhiduoduoAmount = projectMapper.getTotalZddAmountByUserId(userid, from, to, zddStatus);
		BigDecimal crowdsourceAmount = crowdsourceProjectItemMapper.getTotalCrowdsourceAmountByUserid(userid, from, to, crowdsourceStatus);
		BigDecimal entrustAmount = entrustmentProjectItemMapper.getTotalEntrustAmountByUserid(userid, from, to, entrustStatus);
		return zhiduoduoAmount.add(crowdsourceAmount).add(entrustAmount);
	}

	@Override
	public MakerYearAmountDto getUserYearAmounts(int userid, int calcAmountType, int year) {
		MakerYearAmountDto dto = MakerYearAmountDto.of(year);
		// 智众包创客的智众包项目款,只有在计算 项目的季度/年度总金额时才会包含智众包项目款
		BigDecimal zhiduoduoAmount = projectMapper.getYearlyTotalAmountByStates(userid, 0,
				CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year);
		// 委托发单
		BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserYearTotalEntrustProjectAmountByStates(userid,
				CalcAmountType.getEntrustProjectStates(calcAmountType), year);
		// 创客团金额
		BigDecimal grouponAmount = entrustmentProjectItemMapper.sumUserYearTotalMakerGrouponProjectAmountByStates(userid,
				CalcAmountType.getEntrustProjectStates(calcAmountType), year);
		// 智众包项目金额，判断是否需要包含智众包项目
		BigDecimal crowdsourceAmount;
		if (calcAmountType == CalcAmountType.ALL) {
			crowdsourceAmount = crowdsourceProjectItemMapper.getYearlyTotalProjectAmount(userid, CrowdsourceUserType.STUDIO,0, 0, year);
		} else {
			crowdsourceAmount = crowdsourceProjectItemMapper.getYearlyTotalProjectAmountByStates(userid, CrowdsourceUserType.STUDIO, 0, 0, CalcAmountType.getCrowdsourceProjectStates(calcAmountType), year);
		}
		// 纯代理
		BigDecimal agentTaxerAmount = taxerInvoiceMapper.getYearAgentTaxerTotalAmount(userid, 0, year);
		//  交易额
		BigDecimal taxerAmount = taxerInvoiceMapper.getYearTaxerTotalAmount(userid, 0, year);

		BigDecimal totalAmount = zhiduoduoAmount.add(entrustAmount)
				.add(grouponAmount)
				.add(crowdsourceAmount)
				.add(agentTaxerAmount)
				.add(taxerAmount);

		dto.setZddAmount(zhiduoduoAmount)
		   .setEntrustAmount(entrustAmount)
		   .setMakerGrouponAmount(grouponAmount)
		   .setCrowdsourceAmount(crowdsourceAmount)
		   .setAgentTaxerAmount(agentTaxerAmount)
		   .setTaxerAmount(taxerAmount)
		   .setTotalAmount(totalAmount);
		return dto;
	}

	@Override
	public BigDecimal getTotalAmountByUserIdno(String idno, int projectid,int projectType, int calcAmountType, int timeType) {
		if (StringUtils.isBlank(idno)) {
			return BigDecimal.ZERO;
		}
		//  项目金额
		BigDecimal zddAmount = BigDecimal.ZERO;
		// 智众包项目总金额
		BigDecimal croOddAmount = BigDecimal.ZERO;
		BigDecimal taxerAmount = BigDecimal.ZERO;
		// 委托接单+创客团项目金额
		BigDecimal entrustAndGroupAmount = BigDecimal.ZERO;
		if(idno.contains("off")){
			idno = idno.replaceAll("off","").trim();
		}
		// 查询身份证号下的所有创客id
		String userMakerIds = makerMapper.getUserIdsByIdno(idno, idno + "off", idno + "offoff");
		if(StringUtils.isNotBlank(userMakerIds)){
			//  项目总金额
			zddAmount = zddAmount.add(projectMapper.getZddAmountByUserIds(userMakerIds, ProjectType.isZhiduoduoProject(projectType) ? projectid : 0, CalcAmountType.getZhiduoduoProjectStates(calcAmountType), timeType));
			// 智众包项目总金额
			if (calcAmountType == CalcAmountType.ALL) {
				croOddAmount = croOddAmount.add(crowdsourceProjectItemMapper.getCroOddAllAmountByUserIds(userMakerIds, CrowdsourceUserType.STUDIO, ProjectType.isCrowdsourceProject(projectType) ? projectid : 0, timeType));
			} else {
				croOddAmount = croOddAmount.add(crowdsourceProjectItemMapper.getCroOddAmountByUserIds(userMakerIds, CrowdsourceUserType.STUDIO, ProjectType.isCrowdsourceProject(projectType) ? projectid : 0, CalcAmountType.getCrowdsourceProjectStates(calcAmountType), timeType));
			}
			// 纯代理项目金额
			taxerAmount = taxerAmount.add(taxerInvoiceMapper.getTaxerAmountByUserIds(userMakerIds,ProjectType.TAXER == projectType ? projectid : 0,timeType));
			// 委托接单+创客团 项目金额
			entrustAndGroupAmount = entrustmentProjectItemMapper.getEntrustAmountByUserIds(userMakerIds, ProjectType.isInZddEntrustmentProjectTable(projectType) ? projectid : 0, CalcAmountType.getEntrustProjectStates(calcAmountType), timeType);
		}
		// 查询身份证号下的所有自然人id
		String userCrowdsourceIds = crowdsourceAccountMapper.getUserIdsByIdno(idno);
		if(StringUtils.isNotBlank(userCrowdsourceIds)){
			// 智众包项目总金额
			if (calcAmountType == CalcAmountType.ALL) {
				croOddAmount = croOddAmount.add(crowdsourceProjectItemMapper.getCroOddAllAmountByUserIds(userCrowdsourceIds, CrowdsourceUserType.NATURAL_PERSON, ProjectType.isCrowdsourceProject(projectType) ? projectid : 0, timeType));
			} else {
				croOddAmount = croOddAmount.add(crowdsourceProjectItemMapper.getCroOddAmountByUserIds(userCrowdsourceIds, CrowdsourceUserType.NATURAL_PERSON, ProjectType.isCrowdsourceProject(projectType) ? projectid : 0, CalcAmountType.getCrowdsourceProjectStates(calcAmountType), timeType));
			}
		}
		return zddAmount.add(croOddAmount).add(taxerAmount).add(entrustAndGroupAmount);
	}
}
